package com.CmJava.crowd.interceptor;

import com.CmJava.crowd.entity.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 该类是拦截器，请求经过DispatcherServlet过滤后会经过过滤器HandlerInterceptor的preHandle方法
 如果preHandle返回true，才会请求到controller，
 之后再进入postHandle方法，然后再进入afterCompletion方法
 */


public class AdminIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        //session中没有admin对象
        if (admin==null){
            response.sendRedirect("login.html");
            // 虽然上面直接重定向了，但是需要返回一个false给springmvc框架进行后续工作
            // 不然重定向会失败
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
